﻿#if NET45_OR_GREATER
using System;
using System.Runtime.Serialization;

using Newtonsoft.Json;

using zijian666.Converts.Abstractions;

namespace zijian666.Converts.Json;

/// <summary>
/// 用于处理代理对象的Json转换器工厂
/// </summary>
internal class ProxyObjectJsonConvererFactory : JsonConverter
{

    public override bool CanConvert(Type type)
        => typeof(IObjectReference).IsAssignableFrom(type) || typeof(IObjectProxy).IsAssignableFrom(type);

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        var proxy = (value as IObjectProxy)?.GetActualObject() ?? (value as IObjectReference)?.GetRealObject(default) ?? value;
        if (ReferenceEquals(proxy, value))
        {
            var json = JsonConvert.SerializeObject(proxy);
            writer.WriteRaw(json);
        }
        else
        {
            serializer.Serialize(writer, proxy);
        }
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) => throw new NotImplementedException();
}

#endif